package com.fingard.dsp.bank.directbank.ccblifeicbc02;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.ReqAuthForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.ReqQryAuthForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.ReqQryRecAuthInfo;
import com.fingard.dsp.bank.reqrespobj.authforrec.RetAtsAuthForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.RetAtsQryAuthForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.RetAtsQryRecAuthInfo;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 工行批量代扣授权
 * 
 * 需求描述：
 * 		1、指令代码：ENDIIMPT -- 批量代扣签约提交
 * 		2、指令代码：QENDIIMPT -- 批量代扣签约状态查询
 * @author Cruise
 * @date 2018/10/23
 */
public class CCBLifeICBC02AuthorizeForRec extends CCBLifeICBC02Base implements IAuthorizeForRec {
    @Override
    public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) {
        RetAtsAuthForRec tmpRetAts = new RetAtsAuthForRec(p_req.reqHeader);
        
        try {
        	CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
        	tmpBankHeader.packageID = p_req.reqSeqID;
        	tmpBankHeader.fSeqNo = p_req.reqSeqID;
        	tmpBankHeader.transCode = "ENDIIMPT";
            
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpBankHeader);
            xmlWriter.writeElementString("TotalNum", String.valueOf(p_req.detailCount));
            
            Date tmpDateNow = new Date();

            String dateStr = Format.DateTime17Format.format(tmpDateNow);
            String testDate = getBankConfig().getValueAsString("testDate");
            if (testDate != null && !"".equals(testDate)) {
                dateStr = testDate + dateStr.substring(8, 17);
                String passHour = getBankConfig().getValueAsString("passHours");
                String passMiniue = getBankConfig().getValueAsString("passMiniue");
                if (passHour != null && !"".equals(passHour)) {
//					yyyyMMddHHmmssSSS
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(Format.DateTime17Format.parse(dateStr));
                    cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(passHour));
                    cal.add(Calendar.MINUTE,Integer.parseInt(passMiniue));
                    dateStr = Format.DateTime17Format.format(cal.getTime());

                }
            }
    		 xmlWriter.writeElementString("SignTime", dateStr);

//            xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(new Date()));

            xmlWriter.writeElementString("ContractNo", getBankConfig().getValueAsString("contractNo"));
            String payType = p_req.payType;
            if (StringHelper.isNullOrEmpty(payType)) {
                payType = getBankConfig().getValueAsString("payType");
            }
            xmlWriter.writeElementString("PayType", payType);
            xmlWriter.writeElementString("AcctName", p_req.ownActName);
            xmlWriter.writeElementString("AcctNo", p_req.ownAct);
            xmlWriter.writeElementString("ReqReserved1", p_req.reqReserved1);
            xmlWriter.writeElementString("ReqReserved2", p_req.reqReserved2);
            
            int index = 0;
            while (p_req.readRecord()) {
            	index++;
            	
                xmlWriter.writeStartElement("rd");
                xmlWriter.writeElementString("iSeqno", index + "");
                xmlWriter.writeElementString("PayNo", p_req.readedDetail.authCode);
                xmlWriter.writeElementString("PayAcctName", p_req.readedDetail.oppActName);
                xmlWriter.writeElementString("PayAccNo", p_req.readedDetail.oppAct);
                xmlWriter.writeElementString("CertType", p_req.readedDetail.certType);
                xmlWriter.writeElementString("CertNo", p_req.readedDetail.certNum);
                String bkDeadLine = p_req.readedDetail.deadLine;
                if (StringHelper.hasAnyChar(bkDeadLine)) {
                    bkDeadLine = bkDeadLine.replace("-", "");
                } else {
                	bkDeadLine = getBankConfig().getValueAsString("dealLine");
                }
                xmlWriter.writeElementString("DeadLine", bkDeadLine);
                xmlWriter.writeElementString("ReqReserved3", p_req.readedDetail.reqReserved3);
                xmlWriter.writeElementString("ReqReserved4", p_req.readedDetail.reqReserved4);
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
            
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                if (tmpStrRet[1].startsWith("errorCode＝")) {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpStrRet[1].replace("errorCode＝", "");
                    return tmpRetAts;
                }
                if (tmpStrRet[1].contains("reqData=")) {
                    tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("reqData=") + 8, tmpStrRet[1].length());
                }
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetAts.respCode = "0";
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    if ("0".equals(tmpRetCode)) {
                        tmpRetAts.retCode = "0";
                    } else {
                        tmpRetAts.retCode = "1";
                    }
                    tmpRetAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                    tmpRetAts.serialNo = tmpBkReader.getFirstText("/CMS/eb/pub/SerialNo");
                    tmpRetAts.retMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
        	ex.printStackTrace();
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    @Override
    public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) {
        RetAtsQryAuthForRec tmpRetAts = new RetAtsQryAuthForRec(p_req.reqHeader);
        tmpRetAts.writeStart();
        
        try {
            String tmpRespCode = "";
            String tmpRespInfo = "";
            int qryCount = 0;
            String nextTag = "";
            CCBLifeICBC02Header tmpBankHeader = new CCBLifeICBC02Header();
            tmpBankHeader.transCode = "QENDIIMPT";
            
            while (tmpRespCode.length() == 0) {
                qryCount++;
                tmpBankHeader.packageID = p_req.reqHeader.transSeqID + String.valueOf(qryCount);
                if (tmpBankHeader.packageID.length() > 35) {
                	tmpBankHeader.packageID = tmpBankHeader.packageID.substring(tmpBankHeader.packageID.length() - 35, tmpBankHeader.packageID.length());
                }
                tmpBankHeader.fSeqNo = tmpBankHeader.packageID;
                XmlTextWriter xmlWriter = new XmlTextWriter();
                if (StringHelper.isNullOrEmpty(tmpBankHeader.transCode)) {
                    throw new Exception("未赋值TransCode");
                }
                if (StringHelper.isNullOrEmpty(tmpBankHeader.packageID)) {
                    throw new Exception("未赋值PackageID");
                }
                if (StringHelper.isNullOrEmpty(tmpBankHeader.fSeqNo)) {
                    throw new Exception("未赋值fSeqno");
                }
                xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"GBK\"?>");
                xmlWriter.writeStartElement("CMS");
                xmlWriter.writeStartElement("eb");
                xmlWriter.writeStartElement("pub");
                xmlWriter.writeElementString("TransCode", tmpBankHeader.transCode);
                xmlWriter.writeElementString("CIS", bankFront.org);
                xmlWriter.writeElementString("BankCode", "102");
                xmlWriter.writeElementString("ID", bankFront.keyID);
                Date tmpDateNow = new Date();
                xmlWriter.writeElementString("TranDate", Format.Date8Format.format(tmpDateNow));
                xmlWriter.writeElementString("TranTime", Format.Time9Format.format(tmpDateNow));
                xmlWriter.writeElementString("fSeqno", tmpBankHeader.fSeqNo);
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("out");
                xmlWriter.writeElementString("StartDate", "", true);//查询起始日期
                xmlWriter.writeElementString("EndDate", "", true);//查询截至日期
                xmlWriter.writeElementString("QryfSeqno", p_req.reqSeqID);//待查指令包序号
                xmlWriter.writeElementString("NextTag", nextTag, true);//查询下页标识
                xmlWriter.writeElementString("ReqReserved1", "", true);//提交备用字段1
                xmlWriter.writeElementString("ReqReserved2", "", true);//提交备用字段2

                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                        if (isActiveRetCode(tmpRetCode)) {
                            nextTag = tmpBkReader.getFirstText("/CMS/eb/out/NextTag");
                            String tmpTotalNum = tmpBkReader.getFirstText("/CMS/eb/out/TotalNumber");
                            if (StringHelper.isNullOrEmpty(tmpTotalNum)|| "0".equals(tmpTotalNum)) {
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行返回的交易条数为空";
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
                while (tmpBkReader.read("/CMS/eb/out/rd")) {
                    RetAtsQryAuthForRecDetail tmpDetail = new RetAtsQryAuthForRecDetail();
                    XElement tmpRd = tmpBkReader.readedXElement;
                    tmpDetail.iSeqno = tmpRd.getSingleText("PayNo");
                    tmpDetail.payInfo = tmpRd.getSingleText("iRetMsg");
                    tmpDetail.contractNo = tmpRd.getSingleText("ContractNo");
                    tmpDetail.authCode = tmpRd.getSingleText("PayNo");
                    tmpDetail.oppAct = tmpRd.getSingleText("PayAcctNo");
                    tmpDetail.oppActName = tmpRd.getSingleText("PayAcctName");
                    tmpDetail.deadLine = tmpRd.getSingleText("DeadLine");
                    tmpDetail.payType = tmpRd.getSingleText("PayType");
                    String tmpResult = tmpRd.getSingleText("Result");
                    if ("6".equals(tmpResult) || "8".equals(tmpResult)) {
                        tmpDetail.transState = "3";
                    } else if ("7".equals(tmpResult)) {
                        tmpDetail.transState = "2";
                    } else {
                        tmpDetail.transState = "4";
                    }
                    tmpDetail.payCode = tmpRd.getSingleText("iRetCode");
                    tmpRetAts.writeRetDetail(tmpDetail);
                }

                if (StringHelper.isNullOrEmpty(nextTag)) {
                    break;
                }
            }

            tmpRetAts.respCode = tmpRespCode;
            tmpRetAts.respInfo = tmpRespInfo;
            tmpRetAts.reqSeqID = p_req.reqSeqID;
            if ("0".equals(tmpRespCode) && tmpRetAts.getWriteRdCount() <= 0) {
                tmpRetAts.transState = "4";
            }

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
//        if (tmpRetAts.getWriteRdCount() <= 0) {
//            tmpRetAts.writeRetHead();
//        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }

    @Override
    public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
        return null;
    }
}
